package com.platform.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.platform.base.domain.MeterInfo;
import com.platform.base.domain.ValveInfo;
import com.platform.base.service.IValveInfoService;
import com.platform.common.core.text.Convert;
import com.platform.common.manager.AsyncManager;
import com.platform.common.utils.netty.NettyUtil;
import com.platform.common.utils.rabbit.RabbitUtils;
import com.platform.common.utils.redis.RedisRun;
import com.platform.common.utils.redis.RedisUtil;
import com.platform.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.Valve;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.*;
import java.util.concurrent.CountDownLatch;

/**
 * 阀门定时调度任务
 * 
 * @author platform
 */
@Component("valveTask")
@Slf4j
public class ValveTask
{

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IValveInfoService valveInfoService;

    @Autowired
    private RabbitUtils rabbitUtils;

    /**
     * 根据阀门id采集阀门数据
     * @param valveIds
     */
    public void valveTaskById(String valveIds) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("valve_id", Arrays.asList(Convert.toStrArray(valveIds)));
        List<ValveInfo> valveList = valveInfoService.list(queryWrapper);

        for(ValveInfo valveInfo : valveList){
            //获取采集器高位
            String cenhigh = valveInfo.getCollectorId().substring(0,2);
            //获取采集器低位
            String cenlow = valveInfo.getCollectorId().substring(2,4);
            //判断通道是否存在
            if(!redisUtil.hHasKey("sys-netty", valveInfo.getCollectorId())){
                log.error("采集器" + valveInfo.getCollectorId() + "已离线");
                continue;
            }

            String high = valveInfo.getValveId().substring(0,2);
            String low = valveInfo.getValveId().substring(2,4);
            //控制码
            String cont = "01";
            //计算校验码
            int ll = NettyUtil.get10HexNum(cenhigh)+NettyUtil.get10HexNum(cenlow)+NettyUtil.get10HexNum(high)+NettyUtil.get10HexNum(low)+NettyUtil.get10HexNum(cont);
            String check = NettyUtil.get16HexNum(ll);
            if(check.length()<2){
                check = "0" + check;
            }else{
                check = check.substring(check.length()-2);
            }
            String response = "AA " + cenlow + " " + cenhigh + " 00 00 " + low + " " + high + " " + cont + " 00 00 00 00 00 00 " + check + " FF ";
            String revertStr = response.replace(" ", "");
            rabbitUtils.writeToClient(valveInfo.getCollectorId(), revertStr, "阀门"+valveInfo.getValveId()+"读取数据");
            String address = high+low;
            CountDownLatch countDownLatch = new CountDownLatch(1);
            new Thread(new RedisRun(countDownLatch, redisUtil, address, cont)).start();
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 采集所有阀门数据
     * @throws ParseException
     */
    public void valveTask() {
        List<ValveInfo> collectorList = valveInfoService.selectCollectorInfoEq();
        for(ValveInfo colectorInfo : collectorList){
            AsyncManager.me().execute(checkValve(colectorInfo.getCollectorId()));
        }
    }


    public static TimerTask checkValve(String collectorId){

        RedisUtil redisUtil = SpringUtils.getBean(RedisUtil.class);

        RabbitUtils rabbitUtils = SpringUtils.getBean(RabbitUtils.class);
        return new TimerTask() {
            @Override
            public void run() {
            List<ValveInfo> valveList = SpringUtils.getBean(IValveInfoService.class).selectValveInfoBycollectorId(collectorId);
            for(ValveInfo valveInfo : valveList){
                //获取采集器高位
                String cenhigh = valveInfo.getCollectorId().substring(0,2);
                //获取采集器低位
                String cenlow = valveInfo.getCollectorId().substring(2,4);
                //判断通道是否存在
                if(!redisUtil.hHasKey("sys-netty", valveInfo.getCollectorId())){
                    log.error("采集器" + valveInfo.getCollectorId() + "已离线");
                    continue;
                }

                String high = valveInfo.getValveId().substring(0,2);
                String low = valveInfo.getValveId().substring(2,4);
                //控制码
                String cont = "01";
                //计算校验码
                int ll = NettyUtil.get10HexNum(cenhigh)+NettyUtil.get10HexNum(cenlow)+NettyUtil.get10HexNum(high)+NettyUtil.get10HexNum(low)+NettyUtil.get10HexNum(cont);
                String check = NettyUtil.get16HexNum(ll);
                if(check.length()<2){
                    check = "0" + check;
                }else{
                    check = check.substring(check.length()-2);
                }
                String response = "AA " + cenlow + " " + cenhigh + " 00 00 " + low + " " + high + " " + cont + " 00 00 00 00 00 00 " + check + " FF ";
                String revertStr = response.replace(" ", "");

                rabbitUtils.writeToClient(valveInfo.getCollectorId(), revertStr, "阀门"+valveInfo.getValveId()+"读取数据");
                String address = high+low;
                CountDownLatch countDownLatch = new CountDownLatch(1);
                new Thread(new RedisRun(countDownLatch, redisUtil, address, cont)).start();
                try {
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            }
        };
    }
}
